/**
 *	bbx 
 */
define(function(require, exports, module) {
	"use strict";
	//每一个页面都要引入的工具类
	var CommonTools = require('CommonTools_Core');

	//页面跳转管理类
	var WindowTools = require('WindowTools_Core');
	var studyLogs = require('StudyLogs_Service');
	var systemService = require('System_Service');
	var baseService = require('Base_Service');
	//每一个页面都要引入的工具类
	// initready 要在所有变量初始化做完毕后
	CommonTools.initReady(initData);
	var info;

	/**
	 * @description 初始化数据,结合initReady使用
	 * plus情况为plusready
	 * 其它情况为直接初始化
	 */
	function initData() {
		//引入必备文件,下拉刷新依赖于mui与mustache
		CommonTools.importFile([
			'js/libs/mui.min.js',
			'js/libs/mui.picker.min.js'
		], function() {
			console.log("init");
			mui.init({
				statusBarBackground: '#f7f7f7'
			});
			var data = WindowTools.getExtraDataByKey('data');
			if(data) {
				console.log(data);
				itemShow();
				var info = JSON.parse(data);
				var schooles = document.getElementById('schools');
				schooles.innerHTML = '<option value="' + info.DrivingID + '">' + info.DrivingTitle + '</option>';
				var places = document.getElementById('places');
				places.innerHTML = '<option value="' + info.PlaceID + '">' + info.PlaceName + '</option>';
				var techers = document.getElementById('teacher');
				techers.innerHTML = '<option value="' + info.CoachID + '">' + info.Name + '</option>'
				var courses = document.getElementById('course');
				courses.value = info.CourseType;
				courses.setAttribute('disabled', true);
			} else {
				initSchool();
			}
			WindowTools.preloadTemplate();
			init();
			initCommit();
		});
	}

	/**
	 *@description 日期选择 
	 */
	function showDataPicker() {
		document.getElementById('timepicker').onclick = function() {
			console.log('click');
			var dtPicker = new mui.DtPicker({
				type: 'date'
			});
			dtPicker.show(function(selectItems) {
				document.getElementById('timepicker').innerHTML = selectItems.text;
				uploadDate = selectItems.text;
				updateTimeSelect();
			});
		}
	}
	var totalHours = 0;
	/**
	 * 更新时间选择
	 */
	function updateTimeSelect() {
		if(typeof(plus) != 'undefined'){
			console.log('show loading');
			plus.nativeUI.showWaiting('加载中...');
		}
		var schools = document.getElementById('schools');
		if(schools.selectedIndex >= 0){
			uploadSchool = schools.options[schools.selectedIndex].value;
		}
		var data = {
			'PlaceID': uploadPlace,
			'TimeSoltType': uploadTimeStyle,
			'CourseType': uploadCourseStyle,
			'CoachID': uploadTeacher,
			'Date': uploadDate,
			'SubjectType': uploadStudyType,
			'DrivingID': uploadSchool
		};
		debugger;
		studyLogs.canusetime(data, function(res) {

			totalHours = res.totalHours;
		
			var hourSelect = document.getElementById('hourSelect');
			var allItem = '';
			var total = 0;
			for(var i = res.startTime; i < res.endTime; i++) {
				if(!haveThisHour(res.usedTimes, i) || data.SubjectType == 'Simulate') {
					total = total + 1;
					allItem += '<div class="mui-input-row mui-checkbox"> ' +
						'<label>' + i + '点</label>' +
						'<input name="hours" value="' + i + '" type="checkbox" > </div> ';
				}
			}
			if(total==0){
				mui.toast('没有可用时间');
			}
			hourSelect.innerHTML = allItem;
		});
	}
	/**
	 * 判断当前小时
	 * @param {Object} usedTimes
	 * @param {Object} curTime
	 */
	function haveThisHour(usedTimes, curTime) {
		for(var use = 0; use < usedTimes.length; use++) {
			if(usedTimes[use] == curTime) {
				return true;
			}
		}
		return false;
	}

	function init() {
		showDataPicker();
		getStudyTime();
	}

	var uploadSchool = '';
	var uploadPlace = '';
	var uploadTimeStyle = '';
	var uploadCourseStyle = '';
	var uploadTeacher = '';
	var uploadDate = '';
	var uploadStudyType = '';
	var uploadHours;
	/**
	 * 学校的初始化
	 */
	function initSchool() {
		var user = baseService.getUser();
		var Token = baseService.getToken();
		debugger;
		if(user.ApplyType == 'ZiZhu') {
			systemService.getSchoolList(function(data) {
				var fragment = document.createDocumentFragment();
				for(var i = 0; i < data.length; i++) {
					var item = data[i];
					var option;
					option = document.createElement('option');
					option.setAttribute("value", item.id);
					option.innerHTML = item.name;
					fragment.appendChild(option);
				}
				if(data.length > 0) {
					var schoolId = data[0].id;
					updatePlace(schoolId);
				}
				var dataContainer = document.getElementById('schools');
				dataContainer.innerHTML = '';
				dataContainer.appendChild(fragment);
			});
		} else if(user.ApplyType == 'TuanGou' || user.ApplyType == 'ChuanTong') {

			var schooles = document.getElementById('schools');
			//			schooles.style.display = 'none';
			//			var schooleTitle = document.getElementById('schools_title');
			//			schooleTitle.style.display = 'none';
			schooles.innerHTML = '<option value="' + user.DrivingID + '">' + user.DrivingTitle + '</option>';
			uploadSchool = user.DrivingID;
			updatePlace(user.DrivingID);
		}

	}

	/**
	 * 学校id
	 * @param {Object} schoolId
	 */
	function updatePlace(schoolId) {
		var placesContainer = document.getElementById('places');
		placesContainer.innerHTML = '';
		uploadPlace = '';
		systemService.getPlaces(schoolId, function(res) {
			debugger;
			var fragmentPlace = document.createDocumentFragment();
			for(var m = 0; m < res.length; m++) {
				var placeItem = res[m];
				var option;
				option = document.createElement('option');
				option.setAttribute("value", placeItem.id);
				option.innerHTML = placeItem.name;
				fragmentPlace.appendChild(option);
			}
			if(res.length > 0) {
				var place0 = res[0];
				uploadPlace = place0.id;
				updateCoachs(place0.id);
			}
			placesContainer.appendChild(fragmentPlace);
		});
	}

	/**
	 * 更新教练
	 */
	function updateCoachs(placeId) {
		//需要把教练字段弄空
		var coachsContainer = document.getElementById('teacher');
		coachsContainer.innerHTML = '';
		uploadTeacher = '';
		studyLogs.getCoachs(0, placeId, uploadCourseStyle, false, function(data) {
			debugger;
			var fragment = document.createDocumentFragment();
			for(var i = 0; i < data.length; i++) {
				var item = data[i];
				var option;
				option = document.createElement('option');
				option.setAttribute("value", item.CoachID);
				option.innerHTML = item.Name;
				fragment.appendChild(option);
			}
			if(data.length > 0) {
				uploadTeacher = data[0].CoachID;
			}
			coachsContainer.appendChild(fragment);
		});
	}

	/**
	 * 获取学习的时间
	 */
	function getStudyTime() {
		var schools = document.getElementById("schools");
		schools.addEventListener('change', function(e) { //驾校变化，需要改变场地
			var val = this.options[this.selectedIndex].value;
			uploadSchool = val;
			updatePlace(val);
			clearTime();
		});

		var places = document.getElementById('places');
		if(places.selectedIndex >= 0) {
			uploadPlace = places.options[places.selectedIndex].value;
		}
		places.addEventListener('change', function(e) { //场地变化需要更新教练
			var val = this.options[this.selectedIndex].value;
			uploadPlace = val;
			updateCoachs(val);
			clearTime();
		});

		var studyTime = document.getElementById('studyTime');
		if(studyTime.selectedIndex >= 0){
			uploadTimeStyle = studyTime.options[studyTime.selectedIndex].value;
		}
		studyTime.addEventListener('change', function(e) { //时间变化需要跟新教练
			var val = this.options[this.selectedIndex].value;
			uploadTimeStyle = val;
			console.log(val);
			if(uploadPlace) {
				updateCoachs(uploadPlace);
			}
			clearTime();
		});

		var course = document.getElementById('course');
		if(course.selectedIndex>=0){
			uploadCourseStyle = course.options[course.selectedIndex].value;
		}
		course.addEventListener('change', function(e) {
			var val = this.options[this.selectedIndex].value;
			uploadCourseStyle = val;
			console.log(val);
			if(val == 'Course1' || val == 'Course4') {
				itemHide();
			} else {
				itemShow();
				if(uploadPlace) { //跟新教练
					updateCoachs(uploadPlace);
				}
			}
			clearTime();
		});

		var teacher = document.getElementById('teacher');
		if(teacher.selectedIndex >= 0){
			uploadTeacher = teacher.options[teacher.selectedIndex].value;
		}
		teacher.addEventListener('change', function(e) { //教练选择需要更新时间
			var val = this.options[this.selectedIndex].value;
			uploadTeacher = val;
			console.log(val);
			clearTime();
		});

		var studyType = document.getElementById('study_type');
		if(studyType.selectedIndex >= 0){
			uploadStudyType = studyType.options[studyType.selectedIndex].value;
		}
		studyType.addEventListener('change', function(e) {
			var val = this.options[this.selectedIndex].value;
			uploadStudyType = val;
			console.log(val);
			clearTime();
		});
	}

	/**
	 * 科二科三的显示
	 */
	function itemShow() {
		mui('#schools_title')[0].style.display = '';
		mui('#schools')[0].style.display = '';
		mui('#places_title')[0].style.display = '';
		mui('#places')[0].style.display = '';
		mui('#study_time_title')[0].style.display = '';
		mui('#studyTime')[0].style.display = '';
		mui('#teacher_title')[0].style.display = '';
		mui('#teacher')[0].style.display = '';
		mui('#study_type_title')[0].style.display = '';
		mui('#study_type')[0].style.display = '';
		mui('#timepicker_title')[0].style.display = '';
		mui('#timepicker')[0].style.display = '';
		mui('#hourSelect_title')[0].style.display = '';
		mui('#hourSelect')[0].style.display = '';
	}

	/**
	 * 科一科四的隐藏
	 */
	function itemHide() {
		mui('#schools_title')[0].style.display = 'none';
		mui('#schools')[0].style.display = 'none';
		mui('#places_title')[0].style.display = 'none';
		mui('#places')[0].style.display = 'none';
		mui('#study_time_title')[0].style.display = 'none';
		mui('#studyTime')[0].style.display = 'none';
		mui('#teacher_title')[0].style.display = 'none';
		mui('#teacher')[0].style.display = 'none';
		mui('#study_type_title')[0].style.display = 'none';
		mui('#study_type')[0].style.display = 'none';
		mui('#timepicker_title')[0].style.display = 'none';
		mui('#timepicker')[0].style.display = 'none';
		mui('#hourSelect_title')[0].style.display = 'none';
		mui('#hourSelect')[0].style.display = 'none';
	}

	/**
	 * 清除时间选择
	 */
	function clearTime() {
		mui("#timepicker")[0].innerHTML = '选择日期时间';
		mui('#hourSelect')[0].innerHTML = '';
		uploadDate = '';
		uploadHours = '';
	}

	function initCommit() {
		document.getElementById('commit').onclick = function() {
			console.log('commit');
			var schools = document.getElementById('schools');
			if(schools.selectedIndex >= 0){
				uploadSchool = schools.options[schools.selectedIndex].value;
			}
			debugger;
			getStudyTime();
			var hours = document.getElementsByName('hours');
			var check_val = [];
			for(var key in hours) {
				if(hours[key].checked) {
					check_val.push(hours[key].value);
				}
			}
			uploadHours = check_val;
			if(!uploadHours) {
				mui.toast('没有选择小时');
				return;
			}
			if(totalHours < uploadHours.length) {
				mui.toast('购买的时间不够');
				return;
			}

			var data;
			if(uploadCourseStyle == 'Course1' || uploadCourseStyle == 'Course4') {
				data = {
					"CourseType": uploadCourseStyle,
					"SubjectType": 'Theory',
//					'TimeArray': "",
//					"Times": ""
				};
				debugger;
			} else {
				if(uploadHours.length <= 0) {
					mui.toast('请选择时间');
					return;
				}
				if(uploadPlace == ''){
					mui.toast('请选择场地')
					return;
				}
				if(uploadTeacher == ''){
					mui.toast('请选择教练')
					return;
				}
				if(uploadSchool == ''){
					mui.toast('请选择驾校')
					return;
				}
				data = {
					"PlaceID": uploadPlace,
					"TimeSoltType": uploadTimeStyle,
					"CourseType": uploadCourseStyle,
					"TimeArray": [],
					"Times": !!uploadHours ? uploadHours.join(",") : "",
					"CoachID": uploadTeacher,
					"Date": uploadDate,
					"SubjectType": uploadStudyType,
					'DrivingID': uploadSchool
				};
			}
			debugger;
			studyLogs.add(data, function() {
				//				debugger;
				mui.toast('预约成功');
				//				WindowTools.closeCurrentPage();
			});
		};
	}

});